package com.ruoyi.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.domain.SysDictData;
import com.ruoyi.domain.SysDictType;
import com.ruoyi.mapper.SysDictDataMapper;
import com.ruoyi.mapper.SysDictTypeMapper;

@Service
public class SysDictTypeService {
	
	@Autowired
	private SysDictDataMapper sysDictDataMapper;
	
	@Autowired
	private SysDictTypeMapper sysDictTypeMapper;
	
	public List<SysDictData> selectDictDataByType(String dictType) {
		List<SysDictData> dictDatas = sysDictDataMapper.selectDictDataByType(dictType);
		return dictDatas;
	}

	public List<SysDictType> selectDictTypeList() {
		return sysDictTypeMapper.selectDictTypeList();
	}

	public SysDictType selectDictTypeById(Long dictId) {
		return sysDictTypeMapper.selectDictTypeById(dictId);
	}

	public List<SysDictType> selectDictTypeAll() {
		return sysDictTypeMapper.selectDictTypeAll();
	}

	public boolean checkDictTypeUnique(SysDictType dict) {
		Long dictId  = StringUtils.isNull(dict.getDictId()) ? -1L : dict.getDictId();
		SysDictType dictType = sysDictTypeMapper.checkDictTypeUnique(dict.getDictType());
		if (StringUtils.isNotNull(dictType) && dictType.getDictId().longValue() != dictId.longValue()) {
			return UserConstants.NOT_UNIQUE;
		}
		return UserConstants.UNIQUE;
	}

	public int insertDictType(SysDictType dict) {
		return sysDictTypeMapper.insertDictType(dict);
	}

	public int updateDictType(SysDictType dict) {
		SysDictType oldDict = sysDictTypeMapper.selectDictTypeById(dict.getDictId());
		sysDictDataMapper.updateDictDataType(oldDict.getDictType(),dict.getDictType());
		return sysDictTypeMapper.updateDictType(dict);
	}

	public void deleteDictTypeById(Long dictId) {
		SysDictType dictType = selectDictTypeById(dictId);
        if (sysDictDataMapper.countDictDataByType(dictType.getDictType()) > 0) {
            throw new ServiceException(String.format("已分配,不能删除", dictType.getDictName()));
        }
		sysDictTypeMapper.deleteDictTypeById(dictId);
	}

}
